package com.yitao.cms.service.cmsCashCoupons;

import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.common.excel.DataColumn;
import com.skipper.base.common.excel.DataTable;
import com.skipper.base.common.excel.ExcelConverter;
import com.skipper.base.json.JSONArray;
import com.yitao.client.dto.shopInfo.ShopInfoDto;
import com.yitao.client.model.order.MallOrderCouponsModel;
import com.yitao.client.model.order.MallOrderModel;
import com.yitao.client.model.product.ProductInfoModel;
import com.yitao.client.model.user.UserInfoModel;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.dto.cashCoupons.*;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.service.cashCoupons.CashCouponsService;
import com.yitao.cms.service.order.CmsMallOrderCouponsService;
import com.yitao.cms.service.order.CmsOrderService;
import com.yitao.cms.service.product.ProductCmsService;
import com.yitao.cms.service.shopInfo.CmsShopInfoService;
import com.yitao.cms.service.user.appUser.AppUserService;
import com.yitao.cms.utils.BaseUtils;;
import com.yitao.cms.utils.DateUtils;
import com.yitao.cms.utils.ExcelExportUtil;
import com.yitao.cms.utils.NumberUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: wwl
 * @Date: 2020/3/13 14:36
 * @Description:
 */
@Service
public class CmsCashCouponsService {
    @Autowired
    private CashCouponsService cashCouponsService;
    @Autowired
    private ProductCmsService productCmsService;
    @Autowired
    private CmsShopInfoService shopInfoService;
    @Autowired
    private CmsMallOrderCouponsService cmsMallOrderCouponsService;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private CmsOrderService cmsOrderService;
    private static final String WUMENKAN = "无门槛优惠券";
    private static final String USAGERULE = "满MM元可用";
    private BaseUtils baseUtils = BaseUtils.getInstance();
    private final static Logger logger = LoggerFactory.getLogger(CmsCashCouponsService.class);
    /**
     * 优惠券列表查询
     *
     * @param couponsName
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PagedOutput<CashCouponsListDto> findCashCouponsList(HttpServletRequest request, String couponsName, Integer pageNo, Integer pageSize) {
        PagedInput pagedInput = new PagedInput(pageSize, pageNo);
        OperationUserCmsModel operationUserModel = UserSession.getUserSession(request);
        if (operationUserModel==null || operationUserModel.getId() == null || operationUserModel.getShopId() == null) {
            return new PagedOutput(pagedInput, 0, null);
        }else {
            return cashCouponsService.findCashCouponsList(operationUserModel.getShopId(),couponsName,pageNo,pageSize);
        }
    }

    /**
     * 编辑优惠券信息
     * @param cashCouponsAddDto
     * @param request
     * @return
     */
    public DataOutput saveCashCouponsInfo(@RequestBody CashCouponsAddDto cashCouponsAddDto, HttpServletRequest request){
        OperationUserCmsModel operationUserModel = UserSession.getUserSession(request);
        if (operationUserModel==null || operationUserModel.getId() == null || operationUserModel.getShopId() == null) {
            return baseUtils.getBadErrorMsg("获取登录信息失败，请重新登录!");
        }else {
            cashCouponsAddDto.setUserId(operationUserModel.getId());
            cashCouponsAddDto.setShopId(operationUserModel.getShopId());
            return cashCouponsService.saveCashCouponsInfo(cashCouponsAddDto);
        }
    }

    /**
     * 修改优惠券状态
     * @param request
     * @param couponsId
     * @param couponsStatus
     * @return
     */
    public DataOutput updateCashCouponsStatus(HttpServletRequest request, Long couponsId,Integer couponsStatus) {
        OperationUserCmsModel operationUserModel = UserSession.getUserSession(request);
        if (operationUserModel==null || operationUserModel.getId() == null || operationUserModel.getShopId() == null) {
            return baseUtils.getBadErrorMsg("获取登录信息失败，请重新登录!");
        }else {
            logger.info("优惠券状态修改请求参数：userId:{},shopId:{},couponsId:{},couponsStatus{}", operationUserModel.getId(), operationUserModel.getShopId(), couponsId, couponsStatus);
            return cashCouponsService.updateCashCouponsStatus(operationUserModel.getId(),operationUserModel.getShopId(),couponsId,couponsStatus);
        }
    }

    /**
     * 优惠券复制
     * @param request
     * @param couponsId
     * @return
     */
    public DataOutput cashCouponsInfoCopy(HttpServletRequest request, Long couponsId) {
        OperationUserCmsModel operationUserModel = UserSession.getUserSession(request);
        if (operationUserModel==null || operationUserModel.getId() == null || operationUserModel.getShopId() == null) {
            return baseUtils.getBadErrorMsg("获取登录信息失败，请重新登录!");
        }else {
            logger.info("优惠券状态修改请求参数：userId:{},shopId:{},couponsId:{}", operationUserModel.getId(), operationUserModel.getShopId(), couponsId);
            return cashCouponsService.cashCouponsInfoCopy(operationUserModel.getId(),operationUserModel.getShopId(),couponsId);
        }
    }

    /**
     * 优惠券详情
     * @param request
     * @param couponsId
     * @return
     */
    public DataOutput<CashCouponsDetailDto> cashCouponsInfoDetail(HttpServletRequest request, Long couponsId) {
        OperationUserCmsModel operationUserModel = UserSession.getUserSession(request);
        if (operationUserModel==null || operationUserModel.getId() == null || operationUserModel.getShopId() == null) {
            return baseUtils.getBadErrorMsg("获取登录信息失败，请重新登录!");
        }else {
            logger.info("优惠券状态修改请求参数：userId:{},shopId:{},couponsId:{}", operationUserModel.getId(), operationUserModel.getShopId(), couponsId);
            DataOutput<CashCouponsDetailDto> dataOutput = cashCouponsService.cashCouponsInfoDetail(operationUserModel.getId(),operationUserModel.getShopId(),couponsId);
            if (dataOutput.getStatus().equals(CommonStatus.SUCCESS.getCode())){//补充产品信息
                CashCouponsDetailDto cashCouponsDetailDto = new CashCouponsDetailDto();
                cashCouponsDetailDto = dataOutput.getData();
                if (!CollectionUtils.isEmpty(cashCouponsDetailDto.getProductIdList())){
                    List<CashCouponsProductListDto> productListDtos = productCmsService.findCashCouponsProductInfoListByIDs(cashCouponsDetailDto.getProductIdList(),operationUserModel.getShopId());
                    if (!CollectionUtils.isEmpty(productListDtos)){
                        cashCouponsDetailDto.setProductList(productListDtos);
                        return baseUtils.getSuccessMsg(cashCouponsDetailDto);
                    }
                }

            }
            return dataOutput;
        }
    }
    /**
     * 优惠券推广信息
     * @param request
     * @param couponsId
     * @return
     */
    public DataOutput cashCouponsExpand(HttpServletRequest request, Long couponsId) {
        OperationUserCmsModel operationUserModel = UserSession.getUserSession(request);
        if (operationUserModel==null || operationUserModel.getId() == null || operationUserModel.getShopId() == null) {
            return baseUtils.getBadErrorMsg("获取登录信息失败，请重新登录!");
        }else {
            logger.info("优惠券状态修改请求参数：userId:{},shopId:{},couponsId:{}", operationUserModel.getId(), operationUserModel.getShopId(), couponsId);
            ShopInfoDto shopInfoDto =shopInfoService.getShopInfoById(operationUserModel.getShopId());
            CashCouponsExpandDto cashCouponsExpandDto = new CashCouponsExpandDto();
            if (shopInfoDto!=null){
                BeanUtils.copyProperties(shopInfoDto,cashCouponsExpandDto);
            }
            DataOutput<CashCouponsDetailDto> dataOutput = cashCouponsService.cashCouponsInfoDetail(operationUserModel.getId(),operationUserModel.getShopId(),couponsId);
            if (dataOutput.getStatus().equals(CommonStatus.SUCCESS.getCode())){//补充产品信息
                CashCouponsDetailDto cashCouponsDetailDto = dataOutput.getData();
                if (cashCouponsDetailDto!=null){
                    BeanUtils.copyProperties(cashCouponsDetailDto,cashCouponsExpandDto);
                    if (!CollectionUtils.isEmpty(cashCouponsDetailDto.getProductIdList()) && cashCouponsDetailDto.getProductIdList().size()==1){//补充推广产品信息
                        ProductInfoModel productInfoModel =productCmsService.getProductInfoById(cashCouponsDetailDto.getProductIdList().get(0));
                        if (productInfoModel!=null){
                            CashCouponsExpandProductDto cashCouponsExpandProductDto = new CashCouponsExpandProductDto();
                            BeanUtils.copyProperties(productInfoModel,cashCouponsExpandProductDto);
                            cashCouponsExpandDto.setCashCouponsExpandProductDto(cashCouponsExpandProductDto);
                        }
                    }
                    //补充推广名
                    String faceValueYuan = NumberUtil.centToYuan(cashCouponsExpandDto.getFaceValue());
                    if (cashCouponsDetailDto.getAmountValue()==null||cashCouponsDetailDto.getAmountValue()==0L){
                        cashCouponsExpandDto.setCashCouponsExpandName(WUMENKAN );
                    }else{
                        String amountValueYuan = NumberUtil.centToYuan(cashCouponsExpandDto.getAmountValue());
                        cashCouponsExpandDto.setCashCouponsExpandName(USAGERULE.replace("MM", amountValueYuan)+faceValueYuan + "元");
                    }
                }
            }
            return baseUtils.getSuccessMsg(cashCouponsExpandDto);
        }
    }

    /**
     * 数据导出
     *
     * @param request
     * @param response
     */
    public void cashCouponsExportById(HttpServletRequest request, HttpServletResponse response,Long couponsId
    ) {
        List<MallOrderCouponsModel> list = cmsMallOrderCouponsService.getMallOrderCouponsModelListByCouponsId(couponsId);
       List<CashCouponsExportDto> exportDtos = list.stream().map(it->{
            CashCouponsExportDto cashCouponsExportDto = new CashCouponsExportDto();
            BeanUtils.copyProperties(it,cashCouponsExportDto);
            if (it.getUserId()!=null){
                UserInfoModel userInfoModel = appUserService.getAppUserInfoByUserId(it.getUserId());
                if (userInfoModel!=null){
                    BeanUtils.copyProperties(userInfoModel,cashCouponsExportDto);
                }
            }
            if (it.getOrderId()!=null){
                MallOrderModel mallOrderModel = cmsOrderService.getOrderByOrderId(it.getOrderId());
                if (mallOrderModel!=null){
                    cashCouponsExportDto.setActualAmount(mallOrderModel.getActualAmount());
                    cashCouponsExportDto.setOrderTotalAmount(mallOrderModel.getOrderTotalAmount());
                    cashCouponsExportDto.setPayStatus(mallOrderModel.getPayStatus());
                }
            }
            return cashCouponsExportDto;
        }).collect(Collectors.toList());

         //处理数据
        JSONArray jsonArray = new JSONArray();
        jsonArray.fluentAddAll(exportDtos);
        String fileName = "优惠券使用订单" + DateUtils.nowDate("yyyyMMddHHmmss") + ".xlsx";
        String sheetName = "sheet1";
        try {
            this.setResponseHeader(request, response, fileName);
            OutputStream os = response.getOutputStream();
            ExcelConverter excelConverter = ExcelConverter.forXlsx();
            DataTable dataTable = new DataTable(sheetName);
            List<DataColumn> columns = new ArrayList<>();
            columns.add(new DataColumn("nickName", "用户昵称"));
            columns.add(new DataColumn("phone", "注册手机"));
            columns.add(new DataColumn("couponsId", "优惠券ID"));
            columns.add(new DataColumn("couponsName", "优惠券名称"));
            columns.add(new DataColumn("userGetTimeStr", "领取时间"));
            columns.add(new DataColumn("useTimeStr", "使用时间"));
            columns.add(new DataColumn("orderCode", "订单号"));
            columns.add(new DataColumn("orderTotalAmountYuan", "订单总金额(元)"));
            columns.add(new DataColumn("actualValueYuan", "优惠金额(元)"));
            columns.add(new DataColumn("actualAmountYuan", "实际支付金额(元)"));
            columns.add(new DataColumn("payStatusStr", "支付状态"));
            dataTable.addColumns(columns);
            excelConverter.export(os, dataTable, jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 文件下载
     *
     * @param request
     * @param response
     * @param fileName
     */
    private void setResponseHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel"); // 保存为excel
            response.setHeader("Content-Disposition", "attachment;" + ExcelExportUtil.getFileName(request, fileName));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
